package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Auther 赵乾坤
 * @Date 2021-01-04 16:44
 */
@RestController
@RequestMapping("/api/cart")
public class CartApiController {

    @Autowired
    private CartInfoService cartInfoService;

    //加入购物车
    @GetMapping("/addToCart/{skuId}/{skuNum}")
    public void addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum
            , HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            //未登录
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addToCart(skuId,skuNum,userId);
    }

    //根据skuId查询一个购物车
    @GetMapping("/findCartInfoBySkuId/{skuId}")
    public CartInfo findCartInfoBySkuId(@PathVariable Long skuId, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            //未登录
            userId = AuthContextHolder.getUserTempId(request);
        }
        return cartInfoService.findCartInfoBySkuId(skuId,userId);
    }
    //查询当前用户的所有购物车
    //当前用户 可能是临时用户  可能是真实用户
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        //合并后的购物车
         List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);
         return Result.ok(cartInfoList);
    }

    //选中或取消 购物车
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId, @PathVariable Integer isChecked) {
        cartInfoService.checkCart(skuId, isChecked);
        return Result.ok();
    }

    //商品清单 只查询选中的
    @GetMapping("/findCartListByChecked")
    public List<CartInfo> findCartListByChecked(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);//skuId
        return cartInfoService.findCartListByChecked(userId);
    }



}
